package com.laiqilin.controller.admin;

import com.laiqilin.entity.LoginUser;
import com.laiqilin.entity.User;
import com.laiqilin.service.TokenService;
import com.laiqilin.service.UserService;
import com.laiqilin.utils.JwtUtil;
import com.laiqilin.utils.R;
import io.jsonwebtoken.Claims;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/user")
@Api(tags = "用户登录、注册接口")
public class AdminLoginController {

	@Autowired
	private UserService userService;

	@Autowired
	private TokenService tokenService;

	/**
	 * 用户登录接口
	 *
	 * @param user 用户信息
	 * @return 登录成功的返回结果，包含Token
	 */
	@PostMapping("/login")
	@ApiOperation("登录")
	public R login(
			@ApiParam(value = "登录用户对象", required = true)
			@RequestBody User user) {

		LoginUser loginUser = userService.findById(user.getUsername(), user.getPassword());
		Map<String, Object> map = tokenService.createToken(loginUser);
		return R.ok().data(map);
	}

	/**
	 * 获取用户信息
	 *
	 * @param token 用户的Token
	 * @return 用户信息和头像
	 */
	@GetMapping("/info")
	public R info(@RequestParam("token") String token) {
		Claims claims = JwtUtil.parseToken(token);
		String username = (String) claims.get("username");

		Map<String, Object> map = new HashMap<>();
		map.put("name", username);
		map.put("avatar", "https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif");
		return R.ok().data(map);
	}

	/**
	 * 用户注册接口
	 *
	 * @param user 注册用户的信息
	 * @return 注册成功或失败的响应
	 */
	@PostMapping("/signIn")
	public R userSignIn(@RequestBody User user) {
		boolean success = userService.saveUserMsg(user);
		return success ? R.ok().code(200).message("注册成功") : R.error();
	}
}
